package com.swedne.test.threadSafe;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author zhouruizhan
 * @date on  2020-11-23
 * @describe
 * 模拟不出来人脸识别多次成功问题
 *
 */


public class MultipleThread {

    private static ExecutorService executorService;
    private static ExecutorService singleThread;
    private static volatile boolean isFinish = true;
    private static long successTime;
    private static Random random = new Random();

    public static void main(String[] args) {
        executorService = Executors.newFixedThreadPool(5);
        singleThread = Executors.newSingleThreadExecutor();
        new Thread1().start();
    }

    private static class Thread1 extends Thread {

        @Override
        //1 线程
        public void run() {
            super.run();
            while (true) {
                synchronized (MultipleThread.class) {
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (!isFinish) {
                        continue;
                    }
                    if (System.currentTimeMillis() - successTime <= 3000) {
                        continue;
                    }

                    //2 线程池
                    isFinish = false;
                    executorService.execute(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sleep(1000);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            //3 模拟结果回调线程
                            singleThread.execute(new Runnable() {
                                @Override
                                public void run() {
                                    isFinish = true;
                                    if (random.nextBoolean()){
                                        successTime = System.currentTimeMillis();
                                        String format = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss").format(new Date(System.currentTimeMillis()));
                                        System.out.println("//--------date=" + format);
                                    }
                                }
                            });

                        }
                    });
                }
            }
        }
    }

}
